﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace LenderClearingHouse
{
  public partial class Admin : PageBase
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void gridRehabStatusCodes_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
      GridItem editedItem = e.Item as GridItem;
      EditRehabStatusCodesControl userControl = (EditRehabStatusCodesControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

      string code = (userControl.FindControl("tbCode") as TextBox).Text;
      string description = (userControl.FindControl("tbDescription") as TextBox).Text;
      
      DataAccess da = new DataAccess();
      da.ExecuteProcedure("insertRehabStatusCodes",
        new string[] { "@Code", "@Description" },
        new object[] { code, description });
    }

    protected void gridRehabStatusCodes_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
      GridEditableItem editedItem = e.Item as GridEditableItem;
      EditRehabStatusCodesControl userControl = (EditRehabStatusCodesControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

      string code = (userControl.FindControl("tbCode") as TextBox).Text;
      string description = (userControl.FindControl("tbDescription") as TextBox).Text;
      int rehabStatusCodesId = int.Parse((userControl.FindControl("hfRehabStatusCodesId") as HiddenField).Value);

      DataAccess da = new DataAccess();
      da.ExecuteProcedure("updateRehabStatusCodes",
        new string[] { "@RehabStatusCodesId", "@Code", "@Description" },
        new object[] { rehabStatusCodesId, code, description });
    }

    protected void gridRehabStatusCodes_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        GridDataItem itm = e.Item as GridDataItem;
        int codeId = (int)(sender as RadGrid).MasterTableView.DataKeyValues[itm.ItemIndex]["RehabStatusCodesId"];
        DataTable dt = new DataAccess().GetDataTable("getRehabStatusCodes");
        if (dt.Select("RehabStatusCodesId = " + codeId.ToString() + " and HasProperties = 1").Length > 0)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "key", string.Format("alert('{0}');", "You should delete all properties with this code first"), true);
            e.Canceled = true;
        }
    }    
  }
}